<template>
    <ElTable class="list-table is-border" height="720" border :data="list">
        <ElTableColumn label="客户名称" prop="khmc" align="center"></ElTableColumn>
        <ElTableColumn label="店铺名称" prop="dpmc" align="center"></ElTableColumn>
        <ElTableColumn label="业务名称" prop="ywmc" align="center"></ElTableColumn>
        <ElTableColumn label="收费模式" prop="sfmsVal" align="center"></ElTableColumn>
        <ElTableColumn label="付款方式" prop="fkfsVal" align="center"></ElTableColumn>
        <ElTableColumn label="店铺平台" prop="dpptName" align="center"></ElTableColumn>
        <ElTableColumn label="店铺类目" prop="dplmVal" align="center"></ElTableColumn>
        <ElTableColumn label="续费负责人" prop="xffzr" align="center"></ElTableColumn>
        <ElTableColumn label="业务首次合作时间" prop="ywschzsj" align="center"></ElTableColumn>
        <ElTableColumn label="业务开始时间" prop="ywkssj" align="center"></ElTableColumn>
        <ElTableColumn label="业务结束时间" prop="ywjssj" align="center">
            <template #default="{ row }">
                <el-tag :type="getTagType(row.ywjssj)" effect="dark">
                    {{ row.ywjssj }}
                </el-tag>
            </template>
        </ElTableColumn>
        <ElTableColumn label="操作" align="center" width="180">
            <template #default="{ row }">
                <div style="display: flex; justify-content: center; gap: 10px;">
                    <el-button type="primary" size="small" @click="createOrder(row)">创建续费订单</el-button>
                    <el-button type="success" size="small" @click="viewAll(row)">查看</el-button>
                </div>
            </template>
        </ElTableColumn>
    </ElTable>

    <ElDialog v-model="xfObj.isShow" title="续费订单" width="90%">
        <!-- 已支付区域 -->
        <ElTable class="list-table is-border" border :data="xfObj.yzfObj.yzfList" :span-method="yzfSpanMethod">
            <ElTableColumn label="业务开始时间" prop="ywkssj" align="center" width="110"></ElTableColumn>
            <ElTableColumn label="业务结束时间" prop="ywjssj" align="center" width="110"></ElTableColumn>
            <ElTableColumn label="业务名称" prop="customerShopBusiness.ywmc" align="center" width="200"></ElTableColumn>
            <ElTableColumn label="平台" prop="customerShopBusiness.customerShop.dpptName" align="center" width="80">
            </ElTableColumn>
            <ElTableColumn label="日咨询" align="center" width="140">
                <template #default="{ row, $index }">
                    <div style="display: flex; justify-content: center; align-items: center;">
                        <ElInput v-model="row.rjzxl" style="width: 55px;"></ElInput>
                        <span style="color: #5CA2C9; margin-left: 8px;">{{ row.dailyConsultAvg || '0' }}%</span>
                    </div>
                </template>
            </ElTableColumn>
            <!-- 应收费用列 -->
            <ElTableColumn label="应收" align="center" width="105">
                <template #default="{ row, $index }">
                    <ElInput v-model="xfObj.yzfObj.yzfYsfy" v-if="$index === 0"></ElInput>
                </template>
            </ElTableColumn>
            <ElTableColumn label="多店铺" align="center" width="80">
                <template #default="{ row }">
                    <ElInput v-model="row.dtdfy"></ElInput>
                </template>
            </ElTableColumn>
            <ElTableColumn label="加班" align="center" width="80">
                <template #default="{ row }">
                    <ElInput v-model="row.jbf"></ElInput>
                </template>
            </ElTableColumn>
            <ElTableColumn label="提成" align="center" width="80">
                <template #default="{ row }">
                    <ElInput v-model="row.tc"></ElInput>
                </template>
            </ElTableColumn>
            <ElTableColumn label="绩效" align="center" width="80">
                <template #default="{ row }">
                    <ElInput v-model="row.jx"></ElInput>
                </template>
            </ElTableColumn>
            <ElTableColumn label="其它" align="center" width="80">
                <template #default="{ row }">
                    <ElInput v-model="row.qt"></ElInput>
                </template>
            </ElTableColumn>
            <ElTableColumn label="赔偿" align="center" width="80">
                <template #default="{ row }">
                    <ElInput v-model="row.peic"></ElInput>
                </template>
            </ElTableColumn>
            <ElTableColumn label="其它扣款" align="center" width="80">
                <template #default="{ row }">
                    <ElInput v-model="row.qtkk"></ElInput>
                </template>
            </ElTableColumn>
            <ElTableColumn label="应收汇总" align="center" width="105">
                <template #default="{ row, $index }">
                    <ElInput :disabled="true" v-model="xfObj.yzfObj.yzfYshz" v-if="$index === 0"></ElInput>
                </template>
            </ElTableColumn>
            <ElTableColumn label="已收款" align="center" width="93">
                <template #default="{ row }">
                    <div>
                        {{ xfObj.yzfObj.yzfSkje }}
                    </div>
                    <ElButton type="primary" link @click="openSk(xfObj.yzfObj.yzfBatchId)">收款</ElButton>
                </template>
            </ElTableColumn>
            <ElTableColumn label="已退款" align="center" width="93">
                <template #default="{ row }">
                    <div>
                        {{ xfObj.yzfObj.yzfTkje }}
                    </div>
                    <ElButton type="primary" link @click="openTk(xfObj.yzfObj.yzfBatchId)">退款</ElButton>
                </template>
            </ElTableColumn>
            <ElTableColumn label="待退补" align="center" width="100">
                <template #default="{ row }">
                    <div>
                        <div>
                            <el-tag type="danger" v-if="xfObj.yzfObj.yzfTbje > 0">需补</el-tag>
                            <el-tag v-if="xfObj.yzfObj.yzfTbje < 0">需退</el-tag>
                            <el-tag type="success" v-if="xfObj.yzfObj.yzfTbje == 0">无需退补</el-tag>
                        </div>
                        {{ xfObj.yzfObj.yzfTbje }}
                    </div>
                </template>
            </ElTableColumn>
        </ElTable>
        <div style="margin-top: 10px;margin-bottom: 10px;">
            <ElButton type="primary" @click="saveYzf">保存</ElButton>
        </div>
        <!-- 待续费区域 -->
        <ElTable class="list-table is-border" border :data="xfObj.dxfObj.dxfList" :span-method="yzfSpanMethod1">
            <ElTableColumn label="续费日期" align="center" width="220">
                <template #default="{ row, $index }">
                    <ElDatePicker style="width: 180px;" v-model="xfObj.dxfObj.dxfXfywkssj" format="YYYY-MM-DD"
                        valueFormat="YYYY-MM-DD" clearable v-if="$index === 0" placeholder="开始日期" />
                    <ElDatePicker style="width: 180px;margin-top: 10px;" v-model="xfObj.dxfObj.dxfXfywjssj"
                        format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" clearable v-if="$index === 0" placeholder="结束日期" />
                </template>
            </ElTableColumn>
            <ElTableColumn label="业务名称" prop="customerShopBusiness.ywmc" align="center" width="200"></ElTableColumn>
            <ElTableColumn label="平台" prop="customerShopBusiness.customerShop.dpptName" align="center" width="80">
            </ElTableColumn>
            <ElTableColumn label="日咨询" align="center" width="140">
                <template #default="{ row, $index }">
                    <div style="display: flex; justify-content: center; align-items: center;">
                        <ElInput v-model="row.rjzxl" style="width: 55px;"></ElInput>
                        <span style="color: #5CA2C9; margin-left: 8px;">{{ row.dailyConsultAvg || '0' }}%</span>
                    </div>
                </template>
            </ElTableColumn>
            <ElTableColumn label="应收" align="center" width="105">
                <template #default="{ row, $index }">
                    <ElInput v-model="xfObj.dxfObj.dxfYsfy" v-if="$index === 0"></ElInput>
                </template>
            </ElTableColumn>
            <ElTableColumn label="多店铺" align="center" width="80">
                <template #default="{ row }">
                    <ElInput v-model="row.dtdfy"></ElInput>
                </template>
            </ElTableColumn>
            <ElTableColumn label="加班" align="center" width="80">
                <template #default="{ row }">
                    <ElInput v-model="row.jbf"></ElInput>
                </template>
            </ElTableColumn>
            <ElTableColumn label="提成" align="center" width="80">
                <template #default="{ row }">
                    <ElInput v-model="row.tc"></ElInput>
                </template>
            </ElTableColumn>
            <ElTableColumn label="绩效" align="center" width="80">
                <template #default="{ row }">
                    <ElInput v-model="row.jx"></ElInput>
                </template>
            </ElTableColumn>
            <ElTableColumn label="其它" align="center" width="80">
                <template #default="{ row }">
                    <ElInput v-model="row.qt"></ElInput>
                </template>
            </ElTableColumn>
            <ElTableColumn label="赔偿" align="center" width="80">
                <template #default="{ row }">
                    <ElInput v-model="row.peic"></ElInput>
                </template>
            </ElTableColumn>
            <ElTableColumn label="其它扣款" align="center" width="80">
                <template #default="{ row }">
                    <ElInput v-model="row.qtkk"></ElInput>
                </template>
            </ElTableColumn>
            <ElTableColumn label="应收汇总" align="center" width="105">
                <template #default="{ row, $index }">
                    <ElInput :disabled="true" v-model="xfObj.dxfObj.dxfYshz" v-if="$index === 0"></ElInput>
                </template>
            </ElTableColumn>
            <ElTableColumn label="已收款" align="center" width="93">
                <template #default="{ row }">
                    <div>
                        {{ xfObj.dxfObj.dxfSkje }}
                    </div>
                    <ElButton type="primary" link @click="openSk(xfObj.dxfObj.dxfBatchId)">收款</ElButton>
                </template>
            </ElTableColumn>
            <ElTableColumn label="已退款" align="center" width="93">
                <template #default="{ row }">
                    <div>
                        {{ xfObj.dxfObj.dxfTkje }}
                    </div>
                    <ElButton type="primary" link @click="openTk(xfObj.dxfObj.dxfBatchId)">退款</ElButton>
                </template>
            </ElTableColumn>
            <ElTableColumn label="待退补" align="center" width="100">
                <template #default="{ row }">
                    <div>
                        {{ xfObj.dxfObj.dxfTbje }}
                    </div>
                </template>
            </ElTableColumn>
        </ElTable>
        <div style="margin-top: 10px;">
            <ElButton type="primary" @click="postXfFunc">确定续费</ElButton>
            <ElButton type="warning" @click="saveDxf">暂存</ElButton>
        </div>
    </ElDialog>

    <ElDialog v-model="xfObj.lsIsShow" title="续费历史订单" width="90%">
        <template v-for="(item, index) in xfObj.lsXfData" :key="index">
            <ElTable class="list-table is-border" border :data="item.detailsList"
                :span-method="createSpanMethod(item.detailsList)" style="margin-bottom: 10px;">
                <!-- 表格列定义 -->
                <ElTableColumn label="业务开始时间" prop="ywkssj" align="center" width="110"></ElTableColumn>
                <ElTableColumn label="业务结束时间" prop="ywjssj" align="center" width="110"></ElTableColumn>
                <ElTableColumn label="业务名称" prop="customerShopBusiness.ywmc" align="center" width="200"></ElTableColumn>
                <ElTableColumn label="平台" prop="customerShopBusiness.customerShop.dpptName" align="center" width="80">
                </ElTableColumn>
                <ElTableColumn label="日咨询" prop="rjzxl" align="center" width="125"></ElTableColumn>
                <ElTableColumn label="应收" align="center" prop="ysfy" width="105">
                </ElTableColumn>
                <ElTableColumn label="多店铺" align="center" prop="dtdfy" width="80">
                </ElTableColumn>
                <ElTableColumn label="加班" align="center" prop="jbf" width="80">
                </ElTableColumn>
                <ElTableColumn label="提成" align="center" prop="tc" width="80">
                </ElTableColumn>
                <ElTableColumn label="绩效" align="center" prop="jx" width="80">
                </ElTableColumn>
                <ElTableColumn label="其它" align="center" prop="qt" width="80">
                </ElTableColumn>
                <ElTableColumn label="赔偿" align="center" prop="peic" width="80">
                </ElTableColumn>
                <ElTableColumn label="其它扣款" align="center" prop="qtkk" width="80">
                </ElTableColumn>
                <ElTableColumn label="应收汇总" align="center" prop="yshz" width="105">
                </ElTableColumn>
                <ElTableColumn label="已收款" align="center" prop="skCount" width="93">
                </ElTableColumn>
                <ElTableColumn label="已退款" align="center" prop="tkCount" width="93">
                </ElTableColumn>
                <ElTableColumn label="待退补" align="center" prop="tkCount" width="100">
                </ElTableColumn>
            </ElTable>
        </template>
    </ElDialog>

    <ElDialog v-model="xfObj.skIsShow" title="收款" width="90%">
        <SkList :skBatchId="xfObj.skBatchId" :skList="xfObj.skList" @post-sk="postSk"></SkList>
    </ElDialog>

    <ElDialog v-model="xfObj.tkIsShow" title="退款" width="90%">
        <TkList :tkBatchId="xfObj.tkBatchId" :tkList="xfObj.tkList" @post-tk="postTk"></TkList>
    </ElDialog>
</template>

<script setup lang="ts">
import { ElTable, ElTableColumn, ElButton, ElTag, ElMessage, ElDatePicker, ElMessageBox } from 'element-plus'
import { computed, reactive, watch } from 'vue'
import {
    createRenewOrder, getRenewShouList, postSkList,
    getRenewTuiList, postTkList, postSaveYzfOrder, postSaveDxfOrder, postXf, getRenewHistoryData
} from '../api'
import SkList from './SkList.vue'
import TkList from './TkList.vue'

interface Props {
    data?: any[]
}

const props = withDefaults(defineProps<Props>(), {
    data: () => []
})

const emit = defineEmits(['create-order', 'view-all'])

const list = computed(() => {
    return props.data || []
})

const xfObj = reactive({
    isShow: false,
    lsIsShow: false,
    yzfObj: {
        yzfList: [], // 已支付业务列表
        yzfBatchId: '', // 已支付批次
        yzfYsfy: '', // 已支付应收费用
        yzfYshz: '', // 已支付应收汇总
        yzfSkje: '0.00', // 已支付收款金额
        yzfTkje: '0.00', // 已支付退款金额
        yzfTbje: 0, // 已支付退补金额
    },

    dxfObj: {
        dxfCustomerShopBusinessId: '',
        dxfList: [], // 待续费业务列表
        dxfBatchId: '', // 已支付批次
        dxfXfywkssj: '', // 待续费开始日期
        dxfXfywjssj: '', // 待续费结束日期
        dxfYsfy: '', // 待续费应收费用
        dxfYshz: '', // 待续费应收汇总
        dxfSkje: '0.00', // 待续费收款金额
        dxfTkje: '0.00', // 待续费退款金额
        dxfTbje: 0, // 待续费退补金额
        dxfRjzxlSum: 0
    },

    skBatchId: '', // 收款批次id
    skList: [], // 收款列表
    tkBatchId: '', // 退款批次id
    tkList: [], // 退款列表
    skIsShow: false, // 收款模态框
    tkIsShow: false, // 退款模态框


    lsXfData: []
});



const createOrder = async (row: any) => {
    // 取续费订单及已支付订单
    let res = await createRenewOrder(row);
    console.log(res);
    xfObj.yzfObj.yzfList = res.data[0].detailsList;
    xfObj.yzfObj.yzfBatchId = res.data[0].renewBatchId;
    xfObj.yzfObj.yzfYsfy = res.data[0].ysfy;
    xfObj.yzfObj.yzfYshz = res.data[0].yshz;
    xfObj.yzfObj.yzfSkje = res.data[0].skCount;
    xfObj.yzfObj.yzfTkje = res.data[0].tkCount;

    xfObj.dxfObj.dxfList = res.data[1].detailsList;
    xfObj.dxfObj.dxfBatchId = res.data[1].renewBatchId;
    xfObj.dxfObj.dxfYsfy = res.data[1].ysfy;
    xfObj.dxfObj.dxfYshz = res.data[1].yshz;
    xfObj.dxfObj.dxfSkje = res.data[1].skCount;
    xfObj.dxfObj.dxfTkje = res.data[1].tkCount;
    xfObj.dxfObj.dxfXfywkssj = res.data[1].xfywkssj;
    xfObj.dxfObj.dxfXfywjssj = res.data[1].xfywjssj;
    xfObj.dxfObj.dxfCustomerShopBusinessId = res.data[1].customerShopBusinessId;

    xfObj.isShow = true;
}

const yzfSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
    if (columnIndex === 5 || columnIndex === 13 || columnIndex === 14 || columnIndex === 15 || columnIndex === 16) {
        if (rowIndex === 0) {
            return {
                rowspan: xfObj.yzfObj.yzfList.length,
                colspan: 1
            };
        } else {
            return {
                rowspan: 0,
                colspan: 0
            };
        }
    }
}

const yzfSpanMethod1 = ({ row, column, rowIndex, columnIndex }) => {
    if (columnIndex === 0 || columnIndex === 4 || columnIndex === 12 || columnIndex === 13 || columnIndex === 14 || columnIndex === 15) {
        if (rowIndex === 0) {
            return {
                rowspan: xfObj.dxfObj.dxfList.length,
                colspan: 1
            };
        } else {
            return {
                rowspan: 0,
                colspan: 0
            };
        }
    }
}

const createSpanMethod = (data: any) => {
    console.log(data);
    return ({ row, column, rowIndex, columnIndex }) => {
        if (columnIndex === 5 || columnIndex === 13 || columnIndex === 14 || columnIndex === 15 || columnIndex === 16) {
            if (rowIndex === 0) {
                return {
                    rowspan: data.length,
                    colspan: 1
                };
            } else {
                return {
                    rowspan: 0,
                    colspan: 0
                };
            }
        }
    }
}

const viewAll = async (row: any) => {
    let res = await getRenewHistoryData(row);
    console.log(res);
    xfObj.lsXfData = res;
    xfObj.lsXfData.forEach(item => {
        item.detailsList.forEach(row => {
            row.ysfy = item.ysfy;
            row.yshz = item.yshz; // 把外层的 ysfy 赋值给每一行
            row.skCount = item.skCount;
            row.tkCount = item.tkCount;
        });
    });
    xfObj.lsIsShow = true;
}

// 根据时间差返回tag类型
const getTagType = (dateString: string) => {
    if (!dateString) return 'info'

    const endDate = new Date(dateString)
    const today = new Date()
    const timeDiff = endDate.getTime() - today.getTime()
    const dayDiff = Math.ceil(timeDiff / (1000 * 3600 * 24))

    if (dayDiff <= 3) return 'danger'     // 红色
    if (dayDiff <= 7) return 'warning'    // 黄色
    if (dayDiff <= 15) return 'primary'   // 蓝色
    return 'success'                      // 绿色（超过15天）
}

// 计算应收汇总
const calculateYshz = (type) => {
    // type为1表示计算已支付区域，0表示待续费区域
    const targetObj = type === 1 ? xfObj.yzfObj : xfObj.dxfObj;
    const list = type === 1 ? xfObj.yzfObj.yzfList : xfObj.dxfObj.dxfList;

    let total = parseFloat(targetObj[type === 1 ? 'yzfYsfy' : 'dxfYsfy']) || 0;

    // 需要相加的字段
    const addFields = ['dtdfy', 'jbf', 'tc', 'jx', 'qt'];
    // 需要相减的字段
    const subtractFields = ['peic', 'qtkk'];

    let rjzxlCount = 0;

    list.forEach(row => {
        addFields.forEach(field => {
            total += parseFloat(row[field]) || 0;
        });

        subtractFields.forEach(field => {
            total -= parseFloat(row[field]) || 0;
        });

        // 计算日咨询的平均值
        rjzxlCount = rjzxlCount + Number(row['rjzxl']);
    });

    list.forEach(row => {
        row.dailyConsultAvg = Math.round(row.rjzxl / rjzxlCount * 100);
    })


    console.log(rjzxlCount);

    targetObj[type === 1 ? 'yzfYshz' : 'dxfYshz'] = total.toFixed(2);
};

// 监听已支付模块
watch(() => [...xfObj.yzfObj.yzfList, xfObj.yzfObj.yzfYsfy], () => {
    calculateYshz(1);
}, { deep: true });

// 监听待支付模块
watch(() => [...xfObj.dxfObj.dxfList, xfObj.dxfObj.dxfYsfy], () => {
    calculateYshz(0);
}, { deep: true });


// 计算退补金额
const calculateTbje = (type) => {
    const targetObj = type === 1 ? xfObj.yzfObj : xfObj.dxfObj;
    const yshz = parseFloat(targetObj[type === 1 ? 'yzfYshz' : 'dxfYshz']) || 0;
    const skje = parseFloat(targetObj[type === 1 ? 'yzfSkje' : 'dxfSkje']) || 0;
    const tkje = parseFloat(targetObj[type === 1 ? 'yzfTkje' : 'dxfTkje']) || 0;
    targetObj[type === 1 ? 'yzfTbje' : 'dxfTbje'] = (yshz - skje + tkje).toFixed(2);
};

// 监听已支付 应收汇总、收款金额、退款金额的变化
watch(() => [xfObj.yzfObj.yzfYshz, xfObj.yzfObj.yzfSkje, xfObj.yzfObj.yzfTkje], () => {
    calculateTbje(1);
}, { immediate: true });

// 监听待续费 应收汇总、收款金额、退款金额的变化
watch(() => [xfObj.dxfObj.dxfYshz, xfObj.dxfObj.dxfSkje, xfObj.dxfObj.dxfTkje], () => {
    calculateTbje(0);
}, { immediate: true });


const openSk = async (batchId) => {
    xfObj.skBatchId = batchId;
    let res = await getRenewShouList({ batchId })
    xfObj.skList = res;
    xfObj.skIsShow = true;
}

const openTk = async (batchId) => {
    xfObj.tkBatchId = batchId;
    let res = await getRenewTuiList({ batchId })
    xfObj.tkList = res;
    xfObj.tkIsShow = true;
}

// 提交收款
const postSk = async (data) => {
    let res = await postSkList(data);
    if (res.code === 0) {
        const batchId = data.skBatchId;
        if (batchId === xfObj.yzfObj.yzfBatchId) {
            xfObj.yzfObj.yzfSkje = res.data;
        } else if (batchId === xfObj.dxfObj.dxfBatchId) {
            xfObj.dxfObj.dxfSkje = res.data;
        }
        ElMessage.success('操作成功');
        xfObj.skIsShow = false;
    }
}

// 提交退款
const postTk = async (data) => {
    console.log(data);
    let res = await postTkList(data);
    if (res.code === 0) {
        const batchId = data.tkBatchId;
        if (batchId === xfObj.yzfObj.yzfBatchId) {
            xfObj.yzfObj.yzfTkje = res.data;
        } else if (batchId === xfObj.dxfObj.dxfBatchId) {
            xfObj.dxfObj.dxfTkje = res.data;
        }
        ElMessage.success('操作成功');
        xfObj.tkIsShow = false;
    }
}

const saveYzf = async () => {
    let res = await postSaveYzfOrder(xfObj.yzfObj);
    if (res.code === 0) {
        ElMessage.success('操作成功');
    }
}

const saveDxf = async () => {
    let res = await postSaveDxfOrder({ dxfObj: xfObj.dxfObj, yzfObj: xfObj.yzfObj });
    if (res.code === 0) {
        ElMessage.success('操作成功');
    }
}

const totalRjzxl = computed(() => {
    if (!xfObj.dxfObj.dxfList || xfObj.dxfObj.dxfList.length === 0) {
        return 0;
    }

    return xfObj.dxfObj.dxfList.reduce((sum, item) => {
        // 确保item.rjzxl是数字，如果不是则视为0
        const value = Number(item.rjzxl) || 0;
        return sum + value;
    }, 0);
});

const postXfFunc = async () => {
    await ElMessageBox.confirm('确定续费订单吗？', '提示');
    // 总咨询量
    xfObj.dxfObj.dxfRjzxlSum = totalRjzxl.value
    let res = await postXf({ dxfObj: xfObj.dxfObj, yzfObj: xfObj.yzfObj });
    if (res.code === 0) {
        ElMessage.success('操作成功');
        xfObj.isShow = false;
    } else {
        ElMessage.error(res.msg);
    }
}

</script>

<style scoped>
.list-table {
    width: 100%;
}
</style>